package com.baidu.service;

/**
 * @Author Mawq
 * @Date 2021/9/1 16:19
 * @Version 1.0
 */

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baidu.common.core.BusinessException;
import com.baidu.common.dao.entity.User;
import com.baidu.common.dao.repositoy.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 通过Id查找
     * @param id
     * @return
     */
    public User findById(Integer id){
        return userMapper.selectById(id);
    }


    /**
     * 增加用户
     * @param user
     */
    public void insertUser(User user) {
        validateUser(user);
        userMapper.insert(user);
    }

    /**
     * 更新用户
     * @param user
     */
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    /**
     * 删除用户
     * @param id
     */
    public void deleteUser(Integer id) {
        User userQid = userMapper.selectById(id);
        if (id.equals(userQid.getId())&&userQid!=null){
            userMapper.deleteById(id);
            log.info("删除成功！");
        }else {
            log.info("你输入的用户ID不存在！");
        }
        System.out.println(userQid);
    }


    /**
     * 检查用户信息是否正确
     *
     * @param user 用户信息
     */
    private void validateUser(User user) {
        User user1 = userMapper.selectById(user);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            throw new BusinessException("用户名不能为空");
        }
        if (StrUtil.isBlank(user.getPassword())) {
            throw new BusinessException("用户密码不能为空");
        }
    }
}
